package com.neolix.watch;

import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.neolix.watch.bluetooth.BlueToothUtil;
import com.neolix.watch.bluetooth.BluetoothLeService;
import com.neolix.watch.bluetooth.WatchCommandType;
import com.neolix.watch.util.Constant;
import com.neolix.watch.util.StringUtil;


import org.joda.time.DateTime;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.UUID;

import static com.neolix.watch.NeolixApplication.getInstance;
import static com.neolix.watch.util.StringUtil.formatTimeToString;
import static com.neolix.watch.util.StringUtil.isBlank;
import static com.neolix.watch.util.StringUtil.showText;

public class BluetoothLETestActivity extends NeolixNaviagationBaseActivity {

    private EditText serverUUIDEditText;
    private EditText charatUUDIEditText;
    private EditText dataEidtText;
    private Button readButton;
    private Button writeButton;
    private TextView infoTextView;
    private BluetoothGattService service;
    private BluetoothGattCharacteristic characteristic;

    //    private String suuid="42821a40-e477-11e2-82d0-0002a5d5c51b";
//    private String suuid="42821a40-e477-11e2-82d0-0002a5d5c51b";
//    private String suuid = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee";
//    private String cuuid = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee1e";

    private String suuid = "d973f2e0-b19e-11e2-9e96-0800200c9a66";
    private String cuuid = "d973f2e1-b19e-11e2-9e96-0800200c9a66";
    private Button syncDateTimeButton;

    public BluetoothLETestActivity() {
        super(R.layout.activity_bluetooth_test);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initUi();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mGattUpdateReceiver);
    }


    private void initUi() {
        serverUUIDEditText = (EditText) findViewById(R.id.server_uuid);
        charatUUDIEditText = (EditText) findViewById(R.id.characteristic_uuid);
        dataEidtText = (EditText) findViewById(R.id.data);

        readButton = (Button) findViewById(R.id.read);
        writeButton = (Button) findViewById(R.id.write);
        syncDateTimeButton = (Button) findViewById(R.id.write_time);

        infoTextView = (TextView) findViewById(R.id.info);

        serverUUIDEditText.setText(suuid);
        charatUUDIEditText.setText(cuuid);
        dataEidtText.setText("11");
    }

    private void initListener() {
        writeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!getCharacteristic()) return;

//                git rm -r --cached ignore_file
//                git clean -dn
//                git update-index --assume-unchanged PATH
                if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) {
                    try {
//                        characteristic.setValue(dataEidtText.getText().toString().getBytes("gbk"));
                        characteristic.setValue(formatTimeToString(DateTime.now().toDate()).getBytes("gbk"));
//                        String std=new String(byte b[],"encoding")
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    getInstance().bluetoothLeService.setCharacteristicNotification(characteristic, false);//设置为false面条也可以收到通知
                    characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
                    getInstance().bluetoothLeService.writeCharacteristic(characteristic);
                }
            }
        });

        readButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BluetoothGattCharacteristic characteristic1 = BlueToothUtil.getCharacteristic(WatchCommandType.syncSteps);
                if (characteristic1==null) return;
                getInstance().bluetoothLeService.setCharacteristicNotification(characteristic1, true);
//
////                if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
////                    Log.w(Constant.BLUETOOTH_TAG, "PROPERTY_NOTIFY:true");
////                }
//
                if ((characteristic1.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) != 0) {
                    getInstance().bluetoothLeService.readCharacteristic(characteristic1);
                }
            }
        });

        syncDateTimeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BlueToothUtil.syncDateTime(DateTime.now());
            }
        });
    }

    private boolean getCharacteristic() {
        if (!getInstance().isConnectWatch()) {
            showText("未连接设备");
            return false;
        }

        if (isBlank(serverUUIDEditText.getText().toString())
                || isBlank(charatUUDIEditText.getText().toString())
                || isBlank(dataEidtText.getText().toString())) {

            showText("内容不全");
            return false;
        }
        UUID serviceUUID = UUID.fromString(serverUUIDEditText.getText().toString());
        UUID characteristicUUID = UUID.fromString(charatUUDIEditText.getText().toString());

        service = getInstance().bluetoothLeService.getService(serviceUUID);
        if (service != null) {
            characteristic = getInstance().bluetoothLeService.getCharacteristic(service, characteristicUUID);
            if (characteristic == null) {
                showText("characteristic uuid not support");
                return false;
            }
        } else {
            showText("server uuid not support");
            return false;
        }
        return true;
    }

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (Constant.WatchAction.ACTION_WATCH_WRITE_SYNC_DATE_TIME.equals(action)) {
                //同步时间成功
                Log.i(Constant.BLUETOOTH_TAG, "syncDateTime success");
            }
        }
    };

    private IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.WatchAction.ACTION_WATCH_WRITE_SYNC_DATE_TIME);
        return intentFilter;
    }
}
